import React, { memo, useEffect, useRef } from 'react';
import { useSize } from 'ahooks';

import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';

type EChartOption = EChartsOption | undefined;

export type { EChartOption };

const Echart = (props: {
  options: EChartOption;
  notMerge?: boolean;
  hightLight?: { seriesIndex?: number; dataIndex?: number } | boolean;
  className?: string;
}) => {
  const { options, notMerge, hightLight, className } = props;

  const chartRef = useRef<any>();
  const size = useSize(chartRef);
  const chartInsRef = useRef<echarts.ECharts>();

  // 初始化
  useEffect(() => {
    if (!chartRef.current) return;
    chartInsRef.current = echarts.init(chartRef.current);

    return () => {
      chartInsRef.current?.dispose();
      chartInsRef.current = undefined;
    };
  }, []);

  // 监听 options 的变化
  useEffect(() => {
    if (!chartInsRef.current) return;

    // 当输入的参数是空对象的适合，永远是替换
    chartInsRef.current?.setOption(options ?? {}, !options || notMerge);
  }, [options, notMerge]);

  useEffect(() => {
    if (!hightLight || !chartInsRef.current) return;

    // 自动轮播（只播放第一个序列）
    if (typeof hightLight === 'boolean') {
      let dataIndex = 0;
      const interval = setInterval(() => {
        if (!chartInsRef.current) return;
        const maxLen = (chartInsRef.current.getOption() as any).series?.[0].data.length;
        if (maxLen <= 1) return;

        chartInsRef.current.dispatchAction({ type: 'downplay' });
        chartInsRef.current.dispatchAction({
          type: 'highlight',
          dataIndex,
        });
        dataIndex += 1;
        dataIndex %= maxLen;
      }, 2000);
      return () => clearInterval(interval);
    }
    // 高亮指定要素
    else {
      chartInsRef.current.dispatchAction({ type: 'downplay' });
      chartInsRef.current.dispatchAction({
        type: 'highlight',
        seriesIndex: hightLight.seriesIndex,
        dataIndex: hightLight.dataIndex,
      });
      return () => {};
    }
  }, [hightLight]);

  // 监听 dom 的变化
  useEffect(() => {
    if (!chartInsRef.current) return;
    chartInsRef.current.resize();
  }, [size]);

  return <div ref={chartRef} className={`w-full h-full ${className || ''}`} />;
};

export default memo(Echart);
